import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {StatusEnum} from '../../../core/enum/status.enum';
import {NzMessageService} from 'ng-zorro-antd';
import { QuestionbankService } from '../questionbank-manage/questionbank.service';

declare var $: any;

@Component({
  selector: 'app-questionbank-manage-tree',
  templateUrl: './questionbank-manage-tree.component.html',
  styleUrls: ['./questionbank-manage-tree.component.scss']
})
export class QuestionbankManageTreeComponent implements OnInit {
  @Output() treeClick: EventEmitter<any> = new EventEmitter();
  @Input() isShowButton: boolean; // true则隐藏按钮
  @Input() treeId: string; // 树id;
  @Input() selectOne: string; // 选中的id
  treeAddOrUpdate = true; // 新增 /重命名分类
  newCount = 1; // 新建分类默认名称
  // 试题库试题分类
  nodes = [];
  // 分类树设置
  setting = {
    data: {
      key: {
        name: 'title'
      },
      simpleData: {
        enable: true,
        idKey: 'key'
      },
      keep: {
        parent: true,
        leaf: true
      }
    },
    callback: {
      onClick: (event, treeId, treeNode) => {
        this.treeClick.emit({
          id: treeNode.key,
          name: treeNode.title,
          pId: treeNode.pId,
          node: treeNode
        });
      },
      onRename: (event, treeId, treeNode) => {
        if (!treeNode.title) {
          // this.message.warning('请填写试题分类名称!');
          this.resetTree();
          return;
        }
        if (this.treeAddOrUpdate) {
          this.service.fycreate({id: treeNode.key, name: treeNode.title, parentId: treeNode.pId}).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
              this.message.success(res.message);
            } else if (res.status === StatusEnum.WARNING) {
              this.message.warning(res.message);
            } else {
              this.message.error(res.message);
            }
            this.resetTree();
          });
        } else {
          this.service.fyupdate({
            id: treeNode.key,
            name: treeNode.title,
            parentId: treeNode.pId
          }).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
              this.message.success(res.message);
            } else if (res.status === StatusEnum.WARNING) {
              this.message.warning(res.message);
            } else {
              this.message.error(res.message);
            }
            this.resetTree();
          });
        }
      }
    },
    view: {
      showIcon: false,
      addHoverDom: (treeId, treeNode) => {
        const aObj = $('#' + treeNode.tId + '_a');
        if ($('#' + treeNode.key + '_edit').length > 0) {
          return;
        }
        let editStr = '<span class="button edit" id="' + treeNode.key + '_edit" title="重命名"></span>'
          + '<span class="button add" style="margin-right: 2px" id="' + treeNode.key + '_add" title="新增"></span>';
        if (treeNode.isSystem == 1) { // 第一层
        } else {
          editStr = editStr + '<span class="button remove" id="' + treeNode.key + '_remove" title="删除"></span>';
        }
        aObj.append(editStr);
        const edit = $('#' + treeNode.key + '_edit');
        const remove = $('#' + treeNode.key + '_remove');
        const add = $('#' + treeNode.key + '_add');
        const zTree = $.fn.zTree.getZTreeObj(this.treeId);
        if (edit) {
          edit.bind('click', () => {
            this.treeAddOrUpdate = false;         // 编辑
            if (treeNode) {
              zTree.editName(treeNode);
            }
          });
        }

        if (add) {
          add.bind('click', () => {
            this.treeAddOrUpdate = true; // 新增子分类
            treeNode.isParent = true;
            const addNode = zTree.addNodes(treeNode, {
              pId: treeNode.id,
              isParent: false,
              name: '新建子分类' + (this.newCount++)
            });
            zTree.editName(addNode[0]);
          });
        }
        if (remove) {
          remove.bind('click', () => {
            this.service.fydelete({id: treeNode.key}).subscribe(res => {
              if (res.status === StatusEnum.SUCCESS) {
                this.message.success(res.message);
              } else if (res.status === StatusEnum.WARNING) {
                this.message.warning(res.message);
              } else {
                this.message.error(res.message);
              }
              this.resetTree();
            });
          });
        }
      },
      removeHoverDom: (treeId, treeNode) => {
        $('#' + treeNode.key + '_edit').remove();
        $('#' + treeNode.key + '_remove').remove();
        $('#' + treeNode.key + '_add').remove();
      }
    }
  };

  constructor(
    private service: QuestionbankService,
    private message: NzMessageService
  ) {
  }

  ngOnInit() {
    setTimeout(() => {
      this.resetTree();
    }, 100);
  }

  resetTree() {
    this.service.typeTree().subscribe(data => {
      if (data.status === StatusEnum.SUCCESS) {
        $.fn.zTree.init($('#' + this.treeId), this.setting, data.datas);
        if (this.treeId) {
          const functionLimitList = $.fn.zTree.getZTreeObj(this.treeId);
          functionLimitList.expandAll(true);
        }
        this.nodes = data.datas;
        if (this.nodes.length > 0) {
          this.treeClick.emit({
            id: data.datas[0].key,
            name: data.datas[0].title,            // 默认顶级名称
            pId: data.datas[0].pId
          });
        }
      }
    });
  }
}
